package com.daykw.wkinfo.task;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.wkinfo.config.NutzDaoConfig;
import com.daykw.wkinfo.http.HttpBase;
import com.daykw.wkinfo.model.ArticleTask;
import com.daykw.wkinfo.model.BizPageTask;
import com.daykw.wkinfo.model.DatePageTask;
import com.daykw.wkinfo.model.TopicPageTask;
import com.daykw.wkinfo.utils.SpringContextHolder;

public class ArticleJob implements Runnable {

	private static Logger logger = Logger.getLogger(ArticleJob.class);

	private String wbOrIp = "law.wkinfo.com.cn";// "law.wkinfo.com.cn";//

	@Override
	public void run() {
		getDateArtacle();
	}

	private void getDateArtacle() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		java.util.Random random = new java.util.Random();
		int r = random.nextInt(100);
		List<DatePageTask> list = dao.query(DatePageTask.class,
				Cnd.wrap("status=0 and  mod(id,100)=" + r + " limit 2"));

		for (DatePageTask page : list) {
			try {
				Thread.sleep(12000);
				this.getArticleList(page.getRetcount(), page.getGroupid(), null, null, page.getStart(), page.getEnd(),
						dao,page.getId(),page.getPage());
				dao.update(DatePageTask.class, Chain.make("status", 2), Cnd.where("id", "=", page.getId()));
				logger.info("下载完毕，范围:" + page.getStart() + "--" + page.getEnd() + ",gname:" + page.getGroupname());
			} catch (Exception e1) {
				dao.update(DatePageTask.class, Chain.make("status", 33), Cnd.where("id", "=", page.getId()));
				logger.error("解析异常");
			}
		}

	}

	private void getSubArtacle() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		java.util.Random random = new java.util.Random();
		int r = random.nextInt(100);
		List<TopicPageTask> list = dao.query(TopicPageTask.class,
				Cnd.wrap("status=0 and  mod(id,100)=" + r + " limit 10"));

		try {
			for (TopicPageTask page : list) {
				Thread.sleep(10000);
				this.getArticleList(page.getRetcount(), page.getGroupid(), page.getTname(), null, page.getStart(),
						page.getEnd(), dao,page.getId(),page.getPage());
				dao.update(TopicPageTask.class, Chain.make("status", 2), Cnd.where("id", "=", page.getId()));
				logger.info("下载完毕，范围:" + page.getStart() + "--" + page.getEnd() + ",topic:" + page.getTname());
			}

		} catch (Exception e1) {

			logger.error("", e1);
		}
	}

	private void getBizArtacle() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		java.util.Random random = new java.util.Random();
		int r = random.nextInt(100);
		List<BizPageTask> list = dao.query(BizPageTask.class, Cnd.wrap("status=0 and  mod(id,100)=" + r + " limit 10"));

		for (BizPageTask page : list) {

			try {
				Thread.sleep(5000);
				this.getArticleList(page.getRetcount(), page.getGroupid(), null, page.getTname(), page.getStart(),
						page.getEnd(), dao,page.getId(),page.getPage());
				dao.update(BizPageTask.class, Chain.make("status", 2), Cnd.where("id", "=", page.getId()));
				logger.info("下载完毕，范围:" + page.getStart() + "--" + page.getEnd() + ",biz:" + page.getTname());
			} catch (Exception e1) {
				dao.update(BizPageTask.class, Chain.make("status", 33), Cnd.where("id", "=", page.getId()));
				logger.error("", e1);
			}
		}

	}

	private void getArticleList(int total, String gid, String subtype, String biztype, String start, String end,
			NutDao dao,Long id,int page) throws Exception {

		Record r = dao.fetch("t_cookie", Cnd.where("id", "=", 1));
		String cookie = r.getString("cookie");
		String idf = r.getString("idf");
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/plain, */*");
		headers.put("Accept-Encoding", "gzip, deflate");
		headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
		headers.put("Appversion", "1.0.0");
		headers.put("Cache-Control", "no-cache");
		headers.put("Content-Type", "application/json;charset=UTF-8");
		headers.put("Cookie", cookie);
		headers.put("Host", wbOrIp);
		headers.put("Identification",idf);
		headers.put("Origin", "http://" + wbOrIp);
		headers.put("Referer", "https://" + wbOrIp + "/legislation/list?mode=advanced");
		headers.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134");
		headers.put("X-Tingyun-Id", "tN6Win9ZeY4;r=19084805");

		int totalCount = total;
		int maxPage = 1;
		int beginIndex = 0;
		if (totalCount % 100 == 0) {
			maxPage = totalCount / 100;
		} else {

			if (totalCount <= 100) {
				maxPage = 1;
			} else {
				maxPage = (totalCount / 100) + 1;
			}

		}
		
		
		for (int i = page; i <= maxPage; i++) {
			beginIndex = (i - 1) * 100;
			String body = "{\"indexId\":\"law.legislation\",\"query\":{\"queryString\":\"*:*\",\"filterQueries\":[\"defaultRangeDoc:1\"],\"filterDates\":[\"promulgatingDate:["
					+ start + " TO " + end + "]\"]},\"searchScope\":{\"treeNodeIds\":[\"" + gid
					+ "\"]},\"relatedIndexQueries\":[],\"sortOrderList\":[{\"sortKey\":\"important\",\"sortDirection\":\"ASC\"},{\"sortKey\":\"promulgatingDate\",\"sortDirection\":\"DESC\"}],\"pageInfo\":{\"limit\":\"100\",\"offset\":"
					+ beginIndex
					+ "},\"otherOptions\":{\"requireLanguage\":\"cn\",\"relatedIndexEnabled\":true,\"groupEnabled\":false,\"smartEnabled\":true,\"buy\":false,\"summaryLengthLimit\":100,\"advanced\":true,\"synonymEnabled\":true,\"isHideBigLib\":0},\"chargingInfo\":{\"useBalance\":true}}";
			HttpBase http = new HttpBase();
			try {
				String html = http.post("http://" + wbOrIp + "/csi/search?r=" + new Date().getTime(), "utf-8", headers,
						body, false);

				while (html == null || html.equals("fail")) {

					Thread.sleep(3000);
					html = http.post("http://" + wbOrIp + "/csi/search?r=" + new Date().getTime(), "utf-8", headers,
							body, false);

				}

				JSONObject json = (JSONObject) JSONObject.parse(html);
				//logger.info(json.toJSONString());
				if (json != null) {
					JSONArray documentList = json.getJSONArray("documentList");
					for (int k = 0; k < documentList.size(); k++) {
						JSONObject doc = documentList.getJSONObject(k);
						String docId = doc.getString("docId");
						String title = doc.getString("title");
						String summary = doc.getString("summary");

						ArticleTask a = dao.fetch(ArticleTask.class, Cnd.where("aid", "=", docId));
						if (a != null) {

							if (StringUtils.isEmpty(subtype) && StringUtils.isEmpty(biztype)) {
								dao.update(ArticleTask.class,
										Chain.make("title", title).add("prop", doc.toJSONString()),
										Cnd.where("aid", "=", docId));
							} else if (!StringUtils.isEmpty(subtype)) {
								dao.update(ArticleTask.class, Chain.make("subtype", subtype).add("title", title)
										.add("prop", doc.toJSONString()), Cnd.where("aid", "=", docId));
							} else if (!StringUtils.isEmpty(biztype)) {
								dao.update(ArticleTask.class, Chain.make("buztype", biztype).add("title", title)
										.add("prop", doc.toJSONString()), Cnd.where("aid", "=", docId));
							}

						} else {
							a = new ArticleTask();
							a.setAid(docId);

							if (!StringUtils.isEmpty(subtype)) {
								a.setSubtype(subtype);
							}

							if (!StringUtils.isEmpty(biztype)) {
								a.setBustype(biztype);
							}

							a.setTitle(title);
							a.setSource(0);

							a.setUrl("https://law.wkinfo.com.cn/legislation/detail/" + docId);
							a.setCreate_time(new Date());
							a.setProp(doc.toJSONString());
							a.setStatus(0);
							try {
								dao.fastInsert(a);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}

			} catch (Exception e) {
				logger.error("解析异常");
				throw new Exception(e);
			}
			dao.update(DatePageTask.class, Chain.make("page", i), Cnd.where("id", "=", id));
			logger.info("####完成" + start + "-" + end + ",page:" + i + "下载####");
			try {
				Thread.sleep(12000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
